import { useState, useRef, useEffect } from 'react';
import MessageComponent from './MessageComponent';
import MessageInput from './MessageInput';
import StatusIndicator from './StatusIndicator';
import ConfigPanel from './ConfigPanel';
import apiService from '../services/apiService';
// 图表数据处理工具已移除，只使用ChartGenerationNode节点数据
import './ChatInterface.css';

const ChatInterface = () => {
  const [messages, setMessages] = useState([
    {
      id: 1,
      type: 'ai',
      answer: '您好！我是AI智能助手，可以帮您进行数据查询、生成图表和回答各种问题。请告诉我您需要什么帮助？',
      timestamp: new Date()
    }
  ]);
  const [isStreaming, setIsStreaming] = useState(false);
  const [status, setStatus] = useState({ text: '就绪', type: 'ready' });
  // const [streamData, setStreamData] = useState([]); // 已移除，不再需要
  const [nodeFlow, setNodeFlow] = useState([]);
  const [showConfigPanel, setShowConfigPanel] = useState(false);
  const messagesEndRef = useRef(null);
  const currentMessageRef = useRef(null);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const handleSendMessage = async (userInput) => {
    if (!userInput.trim() || isStreaming) return;

    // 添加用户消息
    const userMessage = {
      id: Date.now(),
      type: 'user',
      content: userInput,
      timestamp: new Date()
    };

    setMessages(prev => [...prev, userMessage]);
    setIsStreaming(true);
    setStatus({ text: '处理中', type: 'processing' });

    // 清空之前的数据
    setNodeFlow([]);

    // 创建AI消息容器
    const aiMessageId = Date.now() + 1;
    const aiMessage = {
      id: aiMessageId,
      type: 'ai',
      answer: '',
      sql: '',
      data: null,
      chart: null,
      timestamp: new Date()
    };

    setMessages(prev => [...prev, aiMessage]);
    currentMessageRef.current = aiMessageId;

    try {
      // 使用真实的API调用
      await apiService.streamChat(
        userInput,
        // onData 回调
        (data) => {
          processStreamData(data, aiMessageId);
        },
        // onError 回调
        (error) => {
          console.error('API请求错误:', error);
          setStatus({ text: '请求失败', type: 'error' });
          updateAIMessage(aiMessageId, '抱歉，处理您的请求时出现了错误。请检查网络连接或稍后重试。');
        },
        // onComplete 回调
        () => {
          setStatus({ text: '完成', type: 'ready' });
          setIsStreaming(false);
          
          // 流程结束时，将所有未完成的节点标记为已完成
          setNodeFlow(prev => prev.map(node => ({
            ...node,
            status: 'completed'
          })));
        }
      );
    } catch (error) {
      console.error('发送消息失败:', error);
      setStatus({ text: '请求失败', type: 'error' });
      updateAIMessage(aiMessageId, '抱歉，处理您的请求时出现了错误。请检查网络连接或稍后重试。');
      setIsStreaming(false);
    }
  };

  // 处理流式数据
  const processStreamData = (data, messageId) => {
    console.log('处理流式数据:', data);


    // 处理AI回复文本
    if (data.answer) {
      updateAIMessage(messageId, data.answer);
    }

    // 处理SQL
    if (data.sql) {
      updateAIMessage(messageId, null, null, data.sql);
    }

    // 智能检测和处理数据
    const dataResult = apiService.detectAndProcessData(data);
    if (dataResult.found) {
      updateAIMessage(messageId, null, dataResult.data);
    }

    // 处理图表 - 只处理ChartGenerationNode节点数据
    if (data.node === 'ChartGenerationNode' && data.data && data.data.chart) {
      // 直接使用ChartGenerationNode的图表数据（后端已校验）
      const chartConfig = data.data.chart;
      updateAIMessage(messageId, null, null, null, chartConfig);
      console.log('从ChartGenerationNode获取图表数据:', chartConfig);
    }

    // 处理节点流程
    if (data.node) {
      processNode(data);
    }
  };

  // 更新AI消息
  const updateAIMessage = (messageId, answer = null, data = null, sql = null, chart = null) => {
    setMessages(prev => prev.map(msg => {
      if (msg.id === messageId) {
        const updates = {};
        
        // 处理文本回复 - 累积更新
        if (answer !== null && answer !== 'append') {
          updates.answer = msg.answer + answer;
        }
        
        // 处理数据 - 直接替换
        if (data !== null) {
          updates.data = data;
        }
        
        // 处理SQL - 累积更新
        if (sql !== null) {
          updates.sql = msg.sql + sql;
        }
        
        // 处理图表 - 直接替换（避免重复）
        if (chart !== null) {
          updates.chart = chart;
        }
        
        return { ...msg, ...updates };
      }
      return msg;
    }));
  };

  // 处理节点流程
  const processNode = (data) => {
    const nodeName = data.node;
    const nodeData = data.data || {};
    const timestamp = new Date().toLocaleTimeString();
    
    setNodeFlow(prev => {
      // 检查节点是否已存在
      const existingNodeIndex = prev.findIndex(node => node.name === nodeName);
      
      if (existingNodeIndex >= 0) {
        // 更新现有节点
        const updated = [...prev];
        updated[existingNodeIndex] = {
          ...updated[existingNodeIndex],
          data: nodeData,
          timestamp: timestamp,
          status: 'completed'
        };
        return updated;
      } else {
        // 添加新节点
        const nodeInfo = apiService.getNodeInfo(nodeName);
        const newNode = {
          name: nodeName,
          displayName: nodeInfo.displayName,
          description: nodeInfo.description,
          icon: nodeInfo.icon,
          data: nodeData,
          timestamp: timestamp,
          status: nodeName === '__START__' ? 'completed' : 'processing'
        };
        return [...prev, newNode];
      }
    });
  };

  return (
    <div className="chat-container">
      <div className="chat-header">
        <h1>AI智能助手</h1>
        <div className="header-actions">
          <button 
            className="config-btn"
            onClick={() => setShowConfigPanel(true)}
            title="API配置"
          >
            ⚙️
          </button>
          <StatusIndicator status={status} />
        </div>
      </div>
      
      <div className="chat-main">
        <div className="chat-messages">
          {messages.map((message, index) => (
            <MessageComponent 
              key={message.id} 
              message={message} 
              nodeFlow={nodeFlow}
              isStreaming={isStreaming}
              isLatestMessage={index === messages.length - 1 && message.type === 'ai'}
            />
          ))}
          {isStreaming && (
            <div className="typing-indicator">
              <span className="typing-text">AI正在思考</span>
              <div className="typing-dots">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          )}
          <div ref={messagesEndRef} />
        </div>
      </div>
      
      <MessageInput onSend={handleSendMessage} disabled={isStreaming} />
      
      <ConfigPanel 
        isOpen={showConfigPanel} 
        onClose={() => setShowConfigPanel(false)} 
      />
    </div>
  );
};

export default ChatInterface;
